<template>
  <div class="tableColumnSwitch">
    <el-popover popper-class="tableColumnSwitch-popover">
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
        v-if="tableHead.length"
        >全选</el-checkbox
      >
      <span v-else>暂无数据</span>
      <el-checkbox-group v-model="checkList" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="item in tableHead" :label="item.label" :key="item.label">{{
          item.label
        }}</el-checkbox>
      </el-checkbox-group>
      <!-- <el-button type="primary" class="poptip-condition-add handle-btn cp" slot="reference">显示字段</el-button> -->
      <div   class=" tableStats-btn tableStats-btn-active" slot="reference">
        显示字段
      </div>
    </el-popover>
  </div>
</template>

<script>
import { debounce } from "@u/index";
export default {
  data() {
    return {
      checkList: [],
      isIndeterminate: true,
      checkAll: true,
    };
  },
  props: {
    // 表头信息
    tableHead: {
      default: () => {
        return [];
      },
      type: Array,
      required: true,
    },
  },
  computed: {
    checkLabelList() {
      return this.tableHead.map((v) => {
        return v.label;
      });
    },
  },
  created() {
    this.setCheckList();
  },

  methods: {
    // 全选
    handleCheckAllChange: debounce(function (val) {

      this.checkList = val ? this.checkLabelList : [];
      this.isIndeterminate = false;
      this.handleHideShow();
    }, 300),
    // 单选
    handleCheckedCitiesChange: debounce(function (val) {
      let checkedCount = val.length;

      this.checkAll = checkedCount === this.tableHead.length;
 
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableHead.length;
      this.handleHideShow();
    }, 300),

    // 切换
    handleHideShow() {
        
      this.tableHead.forEach((item) => {
        item["isShow"] = false;
      });
        
      // let showList = [];
      this.tableHead.forEach((item) => {
        let showIndex = this.checkList.findIndex((v) => {
          return v == item.label;
        });
        if (showIndex !== -1) item["isShow"] = true;
      });
      // this.$emit("showFields", this.showList);
    },
    setCheckList() {
      this.checkList = this.tableHead.reduce((arr,item)=>{
        if(item.isShow) arr.push(item.label)
        return arr
      },[])
    },
    reset() {
      this.$nextTick(() => {
        this.setCheckList();
      });
    },
  },
};
</script>

<style lang="less" scoped>
.tableColumnSwitch {
  display: inline-block;

  .handle-btn {
    padding: 8px 24px;
    background: #027aff;
    border-radius: 4px;
    color: #ffffff;
    border: 1px solid #027aff;
    line-height: 1;
    font-size: 14px;
  }
}
</style>
